package preprocessing;

import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;


public class Normalize {

    static boolean Classify(Instances instances){
        int len=instances.numInstances(),attribute=instances.numAttributes()-1,i,j;
        boolean success;
        double [][]data=new double[attribute][len];
        double max,min;
        for(i=0;i<attribute;i++){
            max=min=instances.instance(0).value(i);
            for(j=0; j<len;j++){
                data[i][j]=instances.instance(j).value(i);
                if(max<data[i][j]){
                    max=data[i][j];
                }else if(min>data[i][j]){
                    min=data[i][j];
                }
            }
            success=Normalized(instances,data[i],min,max,i,len);
            if(success==true){
                System.out.println(instances.attribute(i).name()+"归一化成功");
            }
        }
        return true;
    }

    static boolean Normalized(Instances instances,double []data,double min,double max,int attribute,int len){
        for(int j=0;j<len;j++){
            data[j]=(data[j]-min)/(max-min);
            instances.instance(j).setValue(attribute,data[j]);
        }
        return true;
    }

    public static void printAttribute(Instances instances)
    {
        int numOfAttributes = instances.numAttributes();
        for(int i = 0; i < numOfAttributes ;++i)
        {
            Attribute attribute = instances.attribute(i);
            System.out.print(attribute.name() + " ");
        }
        System.out.println();
        //打印实例
        int numOfInstance = instances.numInstances();
        for(int i = 0; i < numOfInstance; ++i)
        {
            Instance instance = instances.instance(i);
            System.out.print(instance.toString() + " " + "\n");
        }
    }

    public static void main(String[] args) throws Exception {
        boolean success;
        DataSource source = new DataSource("/home/tang/appdata/weka-3-8-4/data/iris.arff");
        Instances instances= source.getDataSet();
        success=Classify(instances);
        if(success==true){
            System.out.println("数据归一化完成,结果如下：");
            printAttribute(instances);
        }
    }
}
